package com.wyg.epcommonbase.common.util;

/**
 * @Author: WangYongGan
 * @Date: 2021/10/29 9:48
 * @Description:
 */

import com.wyg.epcommonbase.common.funtionInterface.ManyConsumer;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
 * <p>
 * 1. 持有Mapper的单例.
 * 2. 返回值类型转换.
 * 3. 批量转换Collection中的所有对象.
 * 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
 */
public class BeanMapper {
    //copy
    public static void copy(Object src, Object target) {
        if (src != null)
            BeanUtils.copyProperties(src, target);
    }

    @SneakyThrows
    public static<T> T  copyByClass(Object src, Class<T> target) {
        T t = target.newInstance();
        if (src != null) {
            BeanUtils.copyProperties(src, t);
        }
        return t;
    }

    //copyList入口1: 简单list
    public static <T, R> List<R> copyList(List<T> src, Supplier<R> target) {
        return copyList(src, target, null);
    }

    //copyList入口2: 带转换的list
    public static <T, R> List<R> copyList(List<T> src, Supplier<R> target, ManyConsumer applyTow) {
        List<R> list = new ArrayList<>();
        src.forEach(o -> {
            R r = target.get();
            copy(o, r);
            list.add(r);
            if (applyTow != null) {
                applyTow.apply(o, r);
            }
        });
        return list;
    }
}
